import socket
import redis
from django.shortcuts import render, redirect
from dwebsocket import accept_websocket
from rest_framework.views import APIView
from rest_framework.response import Response
from .ser import *
from django.http.response import JsonResponse, HttpResponse
import time
import os
import shutil
import json
from ant_django.settings import FILE_ROOT, FILE_URL

from ant_django.settings import JUHE_KEY


# Create your views here.

class RegitserAPI(APIView):

    def post(self, request):
        data = request.data
        set = User.objects.filter(username=data['username']).first()
        if set:
            return Response({'msg': '用户已存在', 'code': 4000})

        User.objects.create(username=data['username'], password=data['password'], address=data['address'],
                             realname=data['realname'], phone=data['phone'], identity=data['identity'])

        return Response({'msg': '注册成功', 'code': 200})

class FileUpload(APIView):

    def post(self, request):
        file_obj = request.data.get('file')
        file_name = request.data.get('name')
        f_name = request.data.get('f_name')

        path_lis = os.listdir(FILE_ROOT)
        # 创建切片接收目录
        if not f_name in path_lis:
            os.mkdir(FILE_ROOT + '\\{}'.format(f_name))

        filename = FILE_ROOT + '\\{}\\'.format(f_name) + file_name

        with open(filename, 'wb') as f:
            for line in file_obj:
                f.write(line)
        return JsonResponse({'msg': '上传成功'})

    def put(self, request):
        file_num = request.data.get('index')
        file_name = request.data.get('filename')

        files_seve_url = FILE_ROOT + '\\UploadFile\\' + file_name
        files_read_url = FILE_ROOT + '\\{}\\'.format(file_name)

        # 拼接文件
        with open(files_seve_url, 'ab') as f:
            for i in range(int(file_num)):
                url = files_read_url + file_name + str(i)

                with open(url, 'rb') as r:
                    line = r.read()
                    f.write(line)

        # 删除分片目录
        shutil.rmtree(files_read_url)

        return Response({'msg': '拼接完成'})


class LoginAPI(APIView):

    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')

        set = User.objects.filter(username=username, password=password).first()

        if set:
            return Response({'msg': '登陆成功', 'code': 200, 'uid': set.id})
        else:
            return Response({'msg': '登录失败', 'code': 400})


class GetOnLines(APIView):

    def get(self, request):
        r = redis.Redis(host='localhost')
        if 'HTTP_X_FORWARDED_FOR' in request.META:

            ip = request.META.get('HTTP_X_FOGWARDED_FOR')

        else:

            ip = request.META.get('REMOTE_ADDR')

        if r.scard('set_ip'):

            r.sadd('set_ip', ip)

        else:
            r.sadd('set_ip', ip)
            r.expire('set_ip', 30)

        return Response({'online': r.scard('set_ip')})


# 实时刷新在线人数统计
@accept_websocket
def CensusGet(request):
    # 获取本机电脑名
    myname = socket.getfqdn(socket.gethostname())
    # 获取本机ip
    myaddr = socket.gethostbyname(myname)
    print(myname, myaddr)
    # 连接Redis
    r = redis.Redis()

    if request.is_websocket():
        while True:
            # 判断该数据是否存在
            if r.scard("set_ip"):
                # 向集合内添加数据
                r.sadd("set_ip", str(myaddr))
            else:
                r.sadd("set_ip", str(myaddr))
                # 设置过期时间
                r.expire("set_ip", 300)

            my_len = r.scard("set_ip")
            print(my_len, '----LEN----')
            # print(r.scard("set_ip"), '------REDIS------')
            request.websocket.send(json.dumps(my_len))
            # 设置休眠时间
            time.sleep(30)

import requests
class exchange(APIView):

    def get(self,request):

        url = 'http://op.juhe.cn/onebox/exchange/query?'
        key = ('key',JUHE_KEY)
        response = requests.get(url+JUHE_KEY)

        print(response)

import pymongo
import requests
from datetime import datetime
import datetime
# 历史货币汇率
def Rate(request):
    url = "http://www.chinamoney.com.cn/ags/ms/cm-u-bk-ccpr/CcprHisNew?startDate=2021-03-07&endDate=2021-04-07&currency=USD/CNY&pageNum=1&pageSize=30"

    response = requests.get(url)

    result = eval(response.text).get('records')

    myclient = pymongo.MongoClient("mongodb://localhost:27017/")
    mydb = myclient['rate']
    rate = mydb['exchange']

    # //添加数据到mongo
    # for i in result:
    #     date = i.get('date')
    #     exchange = eval(i.get('values')[0])
    #     rate.insert_one({'汇率':exchange,'日期':date})

    # 获取当前时间的前七天的时间
    # 获取当前时间
    my_date = datetime.datetime.now()
    # 计算偏移天数
    offset = datetime.timedelta(days=-6)
    # 得到你想要的日期时间
    re_date = (my_date + offset).strftime('%Y-%m-%d')
    re_date = datetime.datetime.strptime(re_date, '%Y-%m-%d')

    ratelist = []
    datelist = []

    # 获取Mongo中的所有数据
    for i in rate.find():
        date = datetime.datetime.strptime(i['日期'], '%Y-%m-%d')
        # 判断大于第七天日期的数据
        if re_date <= date:
            print(i)
            datelist.append(i['日期'])
            ratelist.append(i['汇率'])
    print(ratelist,datelist)

    return HttpResponse(json.dumps({"ratelist": ratelist, "datelist": datelist}, ensure_ascii=False),content_type="application/json")

import requests
from django.http import HttpResponse, HttpResponseRedirect

import random
import time
import hashlib

import qrcode
from bs4 import BeautifulSoup

def trans_xml_to_dict(data_xml):
    soup = BeautifulSoup(data_xml, features='xml')
    xml = soup.find('xml')  # 解析XML
    if not xml:
        return {}
    data_dict = dict([(item.name, item.text) for item in xml.find_all()])
    return data_dict

def trans_dict_to_xml(data_dict):  # 定义字典转XML的函数
    data_xml = []
    for k in sorted(data_dict.keys()):  # 遍历字典排序后的key
        v = data_dict.get(k)  # 取出字典中key对应的value
        if k == 'detail' and not v.startswith('<![CDATA['):  # 添加XML标记
            v = '<![CDATA[{}]]>'.format(v)
        data_xml.append('<{key}>{value}</{key}>'.format(key=k, value=v))
    return '<xml>{}</xml>'.format(''.join(data_xml))  # 返回XML

def get_sign(data_dict, key):  # 签名函数，参数为签名的数据和密钥
    params_list = sorted(data_dict.items(), key=lambda e: e[0], reverse=False)  # 参数字典倒排序为列表
    params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list) + '&key=' + key
    # 组织参数字符串并在末尾添加商户交易密钥
    md5 = hashlib.md5()  # 使用MD5加密模式
    md5.update(params_str.encode())  # 将参数字符串传入
    sign = md5.hexdigest().upper()  # 完成加密并转为大写
    return sign

def wx_pay(request):

    url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'  # 微信扫码支付接口
    key = '945bec9df3614cffb74e39aba8fbf7d7'  #商户api秘钥
    total_fee = 1 #支付金额，单位分
    body = '123123'  # 商品描述
    out_trade_no = 'order_%s' % random.randrange(100000, 999999)  # 订单编号
    params = {
        'appid': 'wx092344a76b9979ff',  # APPID
        'mch_id': '1602932608',  # 商户号
        'notify_url': 'http://wxpay.v3u.cn/wx_back/',  # 支付域名回调地址
        'product_id': 'goods_%s' % random.randrange(100000, 999999),  # 商品编号
        'trade_type': 'NATIVE',  # 支付类型（扫码支付）
        'spbill_create_ip': '114.254.176.137',  # 发送请求服务器的IP地址
        'total_fee': total_fee,  # 订单总金额
        'out_trade_no': out_trade_no,  # 订单编号
        'body': body,  # 商品描述
        'nonce_str': 'ibuaiVcKdpRxkhJA'  # 字符串
    }
    sign = get_sign(params, key)  # 获取签名
    params.setdefault('sign', sign)  # 添加签名到参数字典
    xml = trans_dict_to_xml(params)  # 转换字典为XML
    response = requests.request('post', url, data=xml)  # 以POST方式向微信公众平台服务器发起请求
    data_dict = trans_xml_to_dict(response.content)  # 将请求返回的数据转为字典
    print(data_dict)
    qrcode_name = out_trade_no + '.png'  # 支付二维码图片保存路径
    if data_dict.get('return_code') == 'SUCCESS':  # 如果请求成功
        img = qrcode.make(data_dict.get('code_url'))  # 创建支付二维码片
        img.save('./static/' + qrcode_name)  # 保存支付二维码
    return HttpResponse(qrcode_name)


# PayPal支付
import paypalrestsdk
from ant_django.settings import PayPalclient_id,PayPalclient_secret


def payment(request):
    paypalrestsdk.configure({
        "mode": "sandbox",  # sandbox代表沙盒
        "client_id": PayPalclient_id,
        "client_secret": PayPalclient_secret})

    payment = paypalrestsdk.Payment({
        "intent": "sale",
        "payer": {
            "payment_method": "paypal"},
        "redirect_urls": {
            "return_url": "http://localhost:8000/my/pay_execute/",  # 支付成功跳转页面
            "cancel_url": "http://localhost:3000/paypal/cancel/"},  # 取消支付页面
        "transactions": [{
            "amount": {
                "total": "50000",
                "currency": "USD"},
            "description": "等身硅胶仿真人杨幂臭juo版充气娃娃"}]})

    if payment.create():
        print("Payment created successfully")
        for link in payment.links:
            if link.rel == "approval_url":
                approval_url = str(link.href)
                print("Redirect for approval: %s" % (approval_url))
                return redirect(approval_url)
    else:
        print(payment.error)
        return HttpResponse("支付失败")


# PayPal回调地址
def payment_execute(request):

    paymentid = request.GET.get("paymentId") #订单id
    payerid = request.GET.get("PayerID")  #支付者id

    payment = paypalrestsdk.Payment.find(paymentid)
    print(payment)

    if payment.execute({"payer_id": payerid}):
        print("支付成功")
        return redirect('http://127.0.0.1:8080/')
    else:
        print(payment.error) # Error Hash
        return HttpResponse("支付失败")

















